#include "sdkconfig.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"

#include "esp_log.h"
#include "my_nvs.hpp"
#include "my_storage.h"
#include "wifi_station.h"
#include "ssid_manager.h"
#include "wifi_configuration_ap.h"

#define TAG "main"


extern "C" void app_main(void)
{
    // Initialize the default event loop
    ESP_ERROR_CHECK(esp_event_loop_create_default());

    // Initialize NVS flash for Wi-Fi configuration
    esp_err_t ret = nvs_flash_init();
    if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
        ESP_ERROR_CHECK(nvs_flash_erase());
        ret = nvs_flash_init();
    }
    ESP_ERROR_CHECK(ret);

    // Get the Wi-Fi configuration
    auto& ssid_list = *(SsidManager::GetInstance().GetSsidList());
    if (ssid_list.empty()) {
        // Start the Wi-Fi configuration AP
        auto& ap = WifiConfigurationAp::GetInstance();
        ap.SetSsidPrefix("ESP32");
        ap.Start();
        return;
    }

    // Otherwise, connect to the Wi-Fi network
    WifiStation::GetInstance().Start();

    while (true) {
        vTaskDelay(pdMS_TO_TICKS(1000));
    }
}